package cn.buk.qms.web;

import static cn.buk.qms.HttpServletUtil.getIpAddr;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.common.util.DateUtil;
import cn.buk.tms.dao.PaymentOrderDao;
import cn.buk.tms.dto.DtoUser;
import cn.buk.tms.dto.UserDto;
import cn.buk.tms.entity.misc.PaymentOrder;
import cn.buk.tms.entity.misc.User;
import cn.buk.tms.sc.SearchUserCriteria;
import cn.buk.qms.service.EnterpriseService;
import cn.buk.qms.service.UserService;

import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 *
 * @author yfdai
 * @date 2017/1/7
 */
@RestController
public class UserController extends BaseController {

  private static final Logger logger = LogManager.getLogger(UserController.class);

  @Value("${owner_enterprise_id}")
  private int ownerId;

  @Override
  @InitBinder("sc")
  public void initBinder1(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("sc.");
  }

  @Autowired
  private UserService userService;

  @Autowired
  private EnterpriseService enterpriseService;

  @Autowired
  private PaymentOrderDao paymentOrderDao;


  /**
   * 搜索当前用户的余额
   *
   * @param request
   * @return
   */
  @RequestMapping(value = {"/searchEntBalance.do", "/user/searchBalance"})
  public UserDto searchEntBalance(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);
    return userService.searchEnterpriseBalance(enterpriseId);
  }


  @RequestMapping("/recharge.do")
  public JsonResult recharge(HttpServletRequest request,
                             @RequestParam("amount") float amount) {
    final int enterpriseId = getEnterpriseId(request);

    JsonResult jsonResult = new JsonResult();

    final int amount0 = (int) amount;
    if (amount0 < 200 || amount0 % 200 != 0) {
      jsonResult.setStatus("ER");
      jsonResult.setErrmsg("充值金额必须是200元的倍数");
      return jsonResult;
    }


    jsonResult.setStatus("OK");


    //保存支付订单
    //商户订单号
    final String outTradeNo = "10" + enterpriseId + "0" + DateUtil.getCurDateTime().getTime();
    PaymentOrder order = new PaymentOrder();
    order.setEnterpriseId(enterpriseId);
    order.setTradeNo(outTradeNo);
    order.setPrice(amount);
    order.setStatus(0);
    paymentOrderDao.create(order);

    final int amount1 = amount > 1.0 ? (int) amount : 1;

    //TODO  根据当前用户id, 读取数据库中alipay参数后,创建alipayService yfdai 2021-10-26
//    String url = alipayService.createPaymentParams(outTradeNo, amount1, "充值");
//
//    logger.info(url);
//
//    jsonResult.setUrl(url);

    return jsonResult;
  }

  @RequestMapping("/buyPoints.do")
  public JsonResult buyPoints(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.buyPoints(enterpriseId);
  }


  /**
   * 修改密码
   *
   * @param request
   * @param currentPassword 当前密码
   * @param newPassword     新密码
   * @param confirmPassword 确认密码
   * @return
   */
  @RequestMapping("/updatePassword.do")
  public JsonResult updatePassword(HttpServletRequest request,
                                   @RequestParam("currentPassword") String currentPassword,
                                   @RequestParam("newPassword") String newPassword,
                                   @RequestParam("confirmPassword") String confirmPassword) {
    final int userId = getUserId(request);
    final String username = getUsername(request);
    final int enterpriseId = getEnterpriseId(request);

    return userService.updateUserPassword(enterpriseId, userId, username, currentPassword, newPassword, confirmPassword);
  }


  /**
   * 搜索员工信息
   *
   * @param request
   * @param sc
   * @return
   */
  @RequestMapping("/employees")
  public CommonDto<UserDto> searchEmployees(HttpServletRequest request,
                                            @ModelAttribute("sc") SearchUserCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    CommonDto<UserDto> commonDto = new CommonDto<>();

    List<User> users = userService.search(enterpriseId, sc);
    List<UserDto> dtos = new ArrayList<>();
    for (User user : users) {
      UserDto dto = new UserDto();
      dtos.add(dto);

      dto.setId(user.getId());
      dto.setEnterpriseId(user.getEnterprise().getId());
      dto.setUsername(user.getUsername());
      dto.setEmpname(user.getEmpname());

      dto.setEmail(user.getEmail());
      dto.setMobileNo(user.getMobileNo());
      dto.setStatus(user.getStatus());
    }

    commonDto.setDataList(dtos);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  /**
   * 每日签到
   *
   * @param request
   * @return
   */
  @RequestMapping(value = {"/userCheckIn.do", "/user/checkIn"})
  public JsonResult checkIn(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);
    final String ip = getIpAddr(request);

    return userService.checkIn(this.ownerId, enterpriseId, userId, ip);
  }

  /**
   * 查找购买的itinerary信息
   */
  @RequestMapping("/searchItineraryInfo.do")
  public JsonResult searchItineraryInfo(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.searchItineraryInfo(enterpriseId);
  }

  /**
   * 查找购买的itinerary信息
   */
  @RequestMapping("/buyItinerary.do")
  public JsonResult buyItinerary(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.buyItinerary(enterpriseId);
  }

  /**
   * 管理组查询用户信息
   */
  @RequestMapping("/getUserDetail.do")
  public DtoUser getUserDetail(HttpServletRequest request,
                               @RequestParam("id") int id) {
    DtoUser dtoUser = new DtoUser();
    final int enterpriseId = getEnterpriseId(request);
    try {
      User user = userService.getUserById(enterpriseId, id);
      if (user != null) {
        dtoUser.setStatus("OK");
        dtoUser.setUser(user);
      } else {
        dtoUser.setStatus("ER");
      }

    } catch (Exception e) {
      logger.warn(e.getMessage());
    }
    return dtoUser;
  }

}
